#![allow(dead_code)]
use serde::{Deserialize, Serialize};
use serde::de::DeserializeOwned;

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(bound(deserialize = "T: DeserializeOwned"))]
#[serde(bound(serialize = "T: Serialize"))]
pub struct AjaxResult<T> {
    pub code: i32,
    pub msg: String,
    pub data: Option<T>,
}

impl<T> AjaxResult<T> {
    // 成功响应 - 带数据
    pub fn succeed(data: T) -> Self {
        Self {
            code: 200,
            msg: "操作成功".to_string(),
            data: Some(data),
        }
    }

    // 成功响应 - 无数据
    pub fn succeed_without_data() -> Self
        where
            T: Default,
    {
        Self {
            code: 200,
            msg: "操作成功".to_string(),
            data: Some(T::default()),
        }
    }

    // 失败响应 - 自定义错误码和消息
    pub fn failed(code: i32, msg: impl Into<String>) -> Self {
        Self {
            code,
            msg: msg.into(),
            data: None,
        }
    }

    // 常见错误 - 参数错误
    pub fn param_error(msg: impl Into<String>) -> Self {
        Self::failed(400, msg)
    }

    // 常见错误 - 未授权
    pub fn unauthorized(msg: impl Into<String>) -> Self {
        Self::failed(401, msg)
    }

    // 常见错误 - 禁止访问
    pub fn forbidden(msg: impl Into<String>) -> Self {
        Self::failed(403, msg)
    }

    // 常见错误 - 资源不存在
    pub fn not_found(msg: impl Into<String>) -> Self {
        Self::failed(404, msg)
    }

    // 常见错误 - 服务器内部错误
    pub fn internal_error(msg: impl Into<String>) -> Self {
        Self::failed(500, msg)
    }

    pub fn from_result<E: ToString>(result: Result<T, E>) -> Self {
        match result {
            Ok(data) => Self::succeed(data),
            Err(err) => Self::failed(500, err.to_string()),
        }
    }
}

// 针对 Option<T> 的扩展
impl<T> AjaxResult<Option<T>> {
    // 处理 Option 类型，成功时有值，失败时返回默认错误
    pub fn from_option(opt: Option<T>, error_msg: impl Into<String>) -> Self {
        match opt {
            Some(data) => Self::succeed(Some(data)),
            None => Self::failed(404, error_msg),
        }
    }
}